package com.leoman.controller.backend;

import com.leoman.common.DataTableFactory;
import com.leoman.controller.common.CommonController;
import com.leoman.entity.Tag;
import com.leoman.service.TagService;
import com.leoman.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 标签管理
 * Created by 涂奕恒 on 2016/12/6.
 */
@Controller
@RequestMapping(value = "backend/tag")
public class TagController extends CommonController {

    @Autowired
    private TagService tagService;

    @RequestMapping("index")
    public String index() {
        return "backend/标签列表";
    }

    @RequestMapping("/list")
    public void list(HttpServletResponse response,
                     Integer draw,
                     Integer start,
                     Integer length) {
        if (null == start || start == 0) {
            start = 1;
        }
        int pageNum = getPageNum(start, length);
        Page<Tag> page = tagService.find(pageNum, length);

        Map<String, Object> result = DataTableFactory.fitting(draw, page);
        WebUtil.printJson(response, result);
    }

    /**
     * 添加or修改标签
     *
     * @param tagId   标签ID
     * @param content 标签名称
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public Integer save(Integer tagId, String content) {
        try {
            return tagService.save(tagId, content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 删除标签
     *
     * @param tagId 标签ID
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Integer delete(Integer tagId) {
        try {
            tagService.deleteById(tagId);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
